﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;

namespace ViewMaker.Core.Wpf
{
    public static class ComboBoxDelKeyBehavior
    {
        public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ComboBoxDelKeyBehavior), new PropertyMetadata(IsEnabledCallback));

        public static bool GetIsEnabled(ComboBox obj)
        {
            return (bool)obj.GetValue(IsEnabledProperty);
        }

        public static void SetIsEnabled(ComboBox obj, bool value)
        {
            obj.SetValue(IsEnabledProperty, value);
        }

        private static void IsEnabledCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as ComboBox;
            if (ele != null)
            {
                if ((bool)args.OldValue)
                {
                    if (ele.CommandBindings.Contains(DeleteCommandBinding)) ele.CommandBindings.Remove(DeleteCommandBinding);
                }
                if ((bool)args.NewValue)
                {
                    if (!ele.CommandBindings.Contains(DeleteCommandBinding)) ele.CommandBindings.Add(DeleteCommandBinding);
                }
            }
        }

        private static readonly CommandBinding DeleteCommandBinding = new CommandBinding(ApplicationCommands.Delete, DelKeyCommand); 
        private static void DelKeyCommand(object sender, ExecutedRoutedEventArgs e) 
        { 
            var comboBox = e.OriginalSource as ComboBox; 
            if (comboBox != null) comboBox.SelectedIndex = -1; 
        }
    }
}
